import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { getToken } from '@/utils/auth' // 验权
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法
import Layout from '@/views/layout/Layout' // Layout 是架构组件，不在后台返回，在文件里单独引入

var getRouter // 用来获取后台拿到的路由
var routeArr = [{
  path: '/',
  component: Layout,
  children: [{
    path: '/order/order/detail',
    name: 'orderDetail',
    meta: {
      title: '订单详情'
    },
    component: _import('/order/order/detail')
  }]
}]
var btn = {}

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      // 这个方法会调用多次  所以路由里有值得情况下就不用去加载路由了
      if (!getRouter) {
        getRouter = getObjArr('menus')
        if (getRouter && getRouter.length && getRouter.length > 0) {
          routerGo(to, next)
        } else {
          store.dispatch('LogOut').then(() => {
            location.reload()
          })
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

function routerGo(to, next) {
  filterAsyncRouter(getRouter) // 过滤路由
  router.addRoutes(routeArr) // 动态添加路由
  router.addRoutes([{
    path: '*',
    component: Layout,
    redirect: '/404',
    children: [{
      path: '/404',
      name: '404',
      component: _import('/404')
    }]
  }])
  store.commit('SET_ROUTERS', getRouter)
  next({ ...to, replace: true })
}

function getObjArr(name) { // localStorage 获取数组对象的方法
  return JSON.parse(window.localStorage.getItem(name))
}

function filterAsyncRouter(asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  asyncRouterMap.forEach(res => {
    if (res.menu.url && res.menu.ismenu === 1 && !res.children) {
      if (!res.children && res.menu.level === 1) {
        routeArr[0].children.push({
          path: res.menu.url,
          component: _import(res.menu.url + '/index'),
          name: res.menu.name,
          meta: { icon: 'form', title: res.menu.name }
        })
      } else {
        routeArr[0].children.push({
          path: res.menu.url,
          component: _import(res.menu.url),
          name: res.menu.name,
          meta: { icon: 'form', title: res.menu.name }
        })
      }
    } else {
      if (res.menu.level === 2 && res.menu.ismenu === 1) {
        routeArr[0].children.push({
          path: res.menu.url,
          component: _import(res.menu.url),
          name: res.menu.name,
          meta: { icon: 'form', title: res.menu.name }
        })
        // 根据res.ment.level为3的数据来控制页面按钮的显示
        btn[res.menu.name] = {}
        res.children.map(r => {
          btn[res.menu.name][r.menu.name] = true
        })
      }
    }
    if (res.children && res.children.length) {
      filterAsyncRouter(res.children)
    }
  })
  localStorage.setItem('btn', JSON.stringify(btn))
  return routeArr
}
